import sys
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import QApplication, QWidget
from sent_ana_api_helper import sent_ana_get_result
from mt_api_helper import mt_get_result
from summary_make_model import SummaryTxt
from MainWin import Ui_Form

# import sys, os
# if hasattr(sys, 'frozen'):
#     os.environ['PATH'] = sys._MEIPASS + ";" + os.environ['PATH']


class MyMainWindow(QWidget, Ui_Form):
    def __init__(self):
        super(MyMainWindow, self).__init__()
        self.setupUi(self)
        # 功能链接槽函数
        self.pushButton.clicked.connect(self.make_abstract)  # 点击生成摘要
        self.pushButton_2.clicked.connect(self.get_from_txt)  # txt读入文章并显示到窗口
        self.pushButton_3.clicked.connect(self.save_to_txt)  # 摘要保存到txt
        self.pushButton_4.clicked.connect(self.hanlp_summ)  # hanlp摘要提取
        self.pushButton_5.clicked.connect(self.text_translate)  # 机器翻译（讯飞api）
        self.pushButton_6.clicked.connect(self.text_sent_analysis)  # 情感分析（讯飞api）
        self.comboBox.addItems(["CN", "EN", "FR"])
        self.comboBox_2.clicked.connect(self.setleft)
        self.rightitem = list()

    def setleft(self):
        left_item = ["CN", "EN", "FR"]
        now_item = self.comboBox.currentText()
        t = []
        for i in left_item:
            if i != now_item:
                t.append(i)
        self.rightitem = t

        # print(self.rightitem)
        self.comboBox_2.clear()
        self.comboBox_2.addItems(list(self.rightitem))



    def get_from_txt(self):
        directory = QtWidgets.QFileDialog.getOpenFileName(self,
                                                          "选择文章所在路径",
                                                          "./",
                                                          "Text Files (*.txt);;All Files (*)")
        with open(directory[0], "r", encoding="utf-8") as f:
            lines = f.readlines()
        str = ""
        for i in lines:
            if '\n' in i:
                str += i[:-2]
        self.textEdit.setPlainText(str)

    def save_to_txt(self):
        abstract = self.textBrowser_2.toPlainText()
        directory = QtWidgets.QFileDialog.getSaveFileName(self,
                                                          "选择结果保存路径",
                                                          "./result.txt",
                                                          "Text Files (*.txt);;All Files (*)")
        with open(directory[0], "w", encoding="utf-8") as f:
            f.write(abstract)

    def make_abstract(self):
        article = self.textEdit.toPlainText()
        obj = SummaryTxt('stopword.txt')
        abstract = obj.summaryScoredtxt(article)
        str = ""
        for i in abstract:
            str += i
        self.textBrowser_2.setTextColor(QtGui.QColor(0, 0, 0))  # 黑色
        self.textBrowser_2.setPlainText(str)

    def hanlp_summ(self):
        article = self.textEdit.toPlainText()
        obj = SummaryTxt('stopword.txt')
        abstract = obj.pyhanlpSummary(article)
        self.textBrowser_2.setTextColor(QtGui.QColor(0, 0, 0))  # 黑色
        self.textBrowser_2.setPlainText(abstract)

    def text_translate(self):
        article = self.textEdit.toPlainText()

        src = self.comboBox.currentText().lower()
        dst = self.comboBox_2.currentText().lower()
        # 请求参数
        x_appid = "a8b07f5d"
        api_key = "dcee551918ce7eea4b46727889685b29"
        APISecret = "ODVkZmJhMzBmZDY0NWRlMzIzYmMyOTQ2"

        if not self.isConnected():
            self.textBrowser_2.setTextColor(QtGui.QColor(255, 0, 0))  # 红色
            self.textBrowser_2.setPlainText("本机无网络连接，请稍后再试！！！")
            return None

        gClass = mt_get_result(x_appid, APISecret, api_key, article, src, dst)
        data = gClass.call_url()
        if isinstance(data, str):  # 联网后报错
            self.textBrowser_2.setTextColor(QtGui.QColor(255, 0, 0))  # 红色
            self.textBrowser_2.setPlainText(data)
            return None
        # print(data)
        result = data['trans_result']['dst']
        self.textBrowser_2.setTextColor(QtGui.QColor(0, 0, 0))  # 黑色
        self.textBrowser_2.setPlainText(result)

    def text_sent_analysis(self):
        article = self.textEdit.toPlainText()
        if not self.isConnected():
            self.textBrowser_2.setTextColor(QtGui.QColor(255, 0, 0))  # 红色
            self.textBrowser_2.setPlainText("本机无网络连接，请稍后再试！！！")
            return None
        if len(article) * 2 > 500:
            self.textBrowser_2.setTextColor(QtGui.QColor(255, 0, 0))  # 红色
            self.textBrowser_2.setPlainText("输入文本长度大于为500字节，无法判断！！！")
            return None
        # 请求参数
        url_sa = "https://ltpapi.xfyun.cn/v2/sa"  # 接口地址
        x_appid = "a8b07f5d"  # 开放平台应用ID
        api_key = "54b451e55ad44768a4d38c0c810c86b5"  # 开放平台应用接口秘钥
        dict_sentiment = {"-1": "贬义", "0": "中性", "1": "褒义"}

        try:
            sa = sent_ana_get_result(url_sa, x_appid, api_key, article)
            score, sentiment = sa.call_url()
        except:
            self.textBrowser_2.setTextColor(QtGui.QColor(255, 0, 0))  # 红色
            self.textBrowser_2.setPlainText("接口调用有误,请查阅接口文档！！！")
        else:
            strs = "置信度：" + str(score) + "\n" + "情感类型：" + dict_sentiment[str(sentiment)]
            self.textBrowser_2.setTextColor(QtGui.QColor(0, 0, 0))  # 黑色
            self.textBrowser_2.setPlainText(strs)

    def isConnected(self):
        import requests
        try:
            html = requests.get("http://www.baidu.com", timeout=2)
        except:
            return False
        return True


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MyMainWindow()
    win.setWindowTitle("DeepText文本处理系统")
    win.setWindowIcon(QtGui.QIcon("ico.ico"))
    win.show()
    sys.exit(app.exec_())
